package com.css.zfzx.data.primary.HddcActivefaultPG.service.impl;

import com.css.zfzx.data.common.Constant;
import com.css.zfzx.data.common.GenerateSiteCodeUtil;
import com.css.zfzx.data.common.ProvinceCityAreaUtil;
import com.css.zfzx.data.postgresql.fxqhPriorityPG.repository.entity.FxqhPriorityPostgresqlEntity;
import com.css.zfzx.data.postgresql.hddcActivefaultPG.repository.HddcActivefaultRepository;
import com.css.zfzx.data.postgresql.hddcActivefaultPG.repository.entity.HddcActivefaultPostgresqlEntity;
import com.css.zfzx.data.postgresql.pgReconciliation.repository.PgReconciliationNativeRepository;
import com.css.zfzx.data.primary.HddcActivefaultPG.repository.HddcActivefaultPGNativeRepository;
import com.css.zfzx.data.primary.HddcActivefaultPG.repository.entity.HddcActivefaultPGEntity;
import com.css.zfzx.data.primary.HddcActivefaultPG.repository.entity.HddcActivefaultPGVo;
import com.css.zfzx.data.primary.HddcActivefaultPG.service.HddcActivefaultPGService;
import com.css.zfzx.data.primary.base.repository.SuperRepository;
import com.css.zfzx.data.primary.base.vo.ProxyVO4;
import com.css.zfzx.data.primary.base.vo.ProxyVO6;
import com.css.zfzx.data.primary.base.vo.ProxyVO7;
import com.css.zfzx.data.thirdary.jgReconciliation.repository.entity.SjtgfJghshYjSjdzbEntity;
import com.css.zfzx.data.thirdary.jgReconciliation.service.ReconciliationService;
import com.css.zfzx.data.util.DateUtil;
import com.css.zfzx.data.util.GeometryUtil;
import com.css.zfzx.data.util.ServerUtil;
import com.vividsolutions.jts.geom.Geometry;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author zyb
 * @date 2020-11-30
 */
@Log4j2
@Service
public class HddcActivefaultPGServiceImpl implements HddcActivefaultPGService {

    private final HddcActivefaultPGNativeRepository hddcActivefaultPGNativeRepository;
    private final HddcActivefaultRepository repository;
    private final PgReconciliationNativeRepository jgNativeRepository;
    private final ReconciliationService reconciliationService;
    @Autowired
    SuperRepository superRepository;
    @Autowired
    public HddcActivefaultPGServiceImpl(HddcActivefaultPGNativeRepository hddcActivefaultPGNativeRepository, HddcActivefaultRepository repository, PgReconciliationNativeRepository jgNativeRepository, ReconciliationService reconciliationService) {
        this.hddcActivefaultPGNativeRepository = hddcActivefaultPGNativeRepository;
        this.repository = repository;
        this.jgNativeRepository = jgNativeRepository;
        this.reconciliationService = reconciliationService;
    }

    /**
     * 库里所有试点县区划的集合
     * String  区划编码
     */
    public static List<String> pioneerCodeList = Arrays.asList(Constant.pioneerCodeList1);
    List<Integer> featureids= new ArrayList<>();
    List<Integer> lastnewids= new ArrayList<>();
    @PostConstruct
    public void init() {
        initFeatureIds();
        initNewIds();
    }

    @Override
    public List<HddcActivefaultPGVo> findVO() {
        List<Object[]> objects = hddcActivefaultPGNativeRepository.findVO();
        List<HddcActivefaultPGVo> list = new ArrayList<>();
        for (Object[] object:objects){
            HddcActivefaultPGVo vo=new HddcActivefaultPGVo();
            vo.setId(String.valueOf(object[0]));
            vo.setName(String.valueOf(object[1]));
            vo.setProvince(String.valueOf(object[2]));
            vo.setCity(String.valueOf(object[3]));
            vo.setArea(String.valueOf(object[4]));
            list.add(vo);
        }
        return list;
    }

    /**
     * 新增数据不包含修改
     *
     * @return
     */
    @Override
    public void findDataCreate() {
        LocalDateTime createTime = repository.findCreateTime();
        //查询新增数据
        List<HddcActivefaultPGEntity> yhDisasterEntities = hddcActivefaultPGNativeRepository.findYhDisastersCreate(createTime);
        if (yhDisasterEntities.size() == 0) {
            System.out.println("hddc_activefault:时间" + new Date() + ",添加查询了数据：" + yhDisasterEntities.size() + " 条");
            return;
        }
        Map<String, String> errorMap = new HashMap<>();
        List<String> list=new ArrayList<>();
        List<HddcActivefaultPostgresqlEntity> saveList = new ArrayList<>();
        int flag = 0;
        String startCode = null;
        try {
            for (HddcActivefaultPGEntity entity : yhDisasterEntities) {
                String uuid = entity.getUuid();
                String code = ProvinceCityAreaUtil.getCode(entity.getProvince(), entity.getCity(), entity.getArea());
                if (code == null) {
                    errorMap.put(uuid, "区划编码获取失败!");
                    // log.error("活动断层线hddc_activefault:时间" + new Date() + ",数据id:{}" + entity.getUuid() + ";区划:{}" +
                    //         entity.getProvince() + entity.getCity() + entity.getArea() + "的区划编码获取失败，请检查后再导入");
                    continue;
                }
                if (!pioneerCodeList.contains(code)) {
                    String cityCode=code.substring(0, 4) + "00";
                    if (!pioneerCodeList.contains(cityCode)){
                        if (!list.contains(entity.getProvince() + entity.getCity() + entity.getArea())){
                            list.add(entity.getProvince() + entity.getCity() + entity.getArea());
                            errorMap.put(entity.getProvince() + entity.getCity() + entity.getArea(), "不属于试点县!");
                        }
                        continue;
                    }
                }
                //检查字段值不为空
                StringBuilder errorMsg = new StringBuilder();
                Map<String, String> methods = new HashMap<>();
                setCheckFields(methods);
                ServerUtil.checkFieldNull(entity, methods, errorMsg);
                if (StringUtils.isNotEmpty(String.valueOf(errorMsg)) || errorMsg.length() > 0) {
                    errorMap.put(uuid, "必填项存在空值!");
                    // log.error("活动断层线hddc_activefault:时间" + new Date() + ",数据id:{}" + entity.getUuid() + ";错误信息:{}" + errorMsg +
                    //         "导入失败！");
                    continue;
                }
                if (!featureids.contains(entity.getFeature())){
                    errorMap.put(uuid, "断层类型不符合规范!");
                    continue;
                }
                if (!lastnewids.contains(entity.getLatestactiveperiod())){
                    errorMap.put(uuid, "最新活动年代不符合规范!");
                    continue;
                }
                HddcActivefaultPostgresqlEntity postgresqlEntity = new HddcActivefaultPostgresqlEntity();
                BeanUtils.copyProperties(entity, postgresqlEntity);
                postgresqlEntity.setDistrict(entity.getArea());

                Geometry geometry = GeometryUtil.setRecArea(entity.getExtends15());
                postgresqlEntity.setExtends5(geometry);

                postgresqlEntity.setFxpcDataidSjgl(entity.getUuid());
                String oldSitCode = null;
                if (flag == 0) {
                    flag++;
                    oldSitCode = repository.getGenerateSiteCode();
                } else {
                    oldSitCode = startCode;
                }
                String generateSiteCode = GenerateSiteCodeUtil.generateSiteCode(code, oldSitCode, "地震活动断层");
                startCode = generateSiteCode;
                postgresqlEntity.setFxpcDcdxbmSjgl(generateSiteCode);
                //根据名称获取行政编码
                if (!StringUtils.isEmpty(entity.getProvince()) && StringUtils.isEmpty(entity.getCity())) {
                    postgresqlEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                }
                if (!StringUtils.isEmpty(entity.getCity()) && StringUtils.isEmpty(entity.getArea())) {
                    postgresqlEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                    postgresqlEntity.setFxpcXzqhbmbSjgl(code.substring(0, 4) + "00");
                }
                if (!StringUtils.isEmpty(entity.getArea())) {
                    postgresqlEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                    postgresqlEntity.setFxpcXzqhbmbSjgl(code.substring(0, 4) + "00");
                    postgresqlEntity.setFxpcXzqhbmcSjgl(code);
                }
                //标识数据的当前状态，如果是新增数据，该字段为I；
                // 如果数据被更新过，该字段为U；如果数据被删除，该字段为D。
                postgresqlEntity.setFxpcSjztSjgl("I");
                //将创建时间转化成字符串形式
                if (entity.getCreateTime() != null) {
                    postgresqlEntity.setFxpcCreatetimeSjgl(DateUtil.getContainsHMS(entity.getCreateTime()));
                }
                //统一都是默认040
                postgresqlEntity.setFxpcSshySjgl("040");
                //日期分片
                postgresqlEntity.setFxpcRqfpSjgl(DateUtil.getNotContainsHMS(new Date()));
                //批次号
                postgresqlEntity.setFxpcPchSjgl(DateUtil.getNotContainsHMS(new Date()));
                //审核流程状态
                postgresqlEntity.setFxpcShlcztSjgl(Constant.SHLCZT_ZZSH);
                //审核状态
                postgresqlEntity.setFxpcShztSjgl(Constant.SHZT_TG);
                saveList.add(postgresqlEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        long startIn = System.currentTimeMillis();
        int iterable = jgNativeRepository.batchSave1(saveList);
        long endIn = System.currentTimeMillis();
        if (errorMap.size() != 0) {
            log.error(errorMap);
        }
        System.out.println("表hddc_activefault:时间" + new Date() + ",插入数据成功：" + saveList.size() + " 条,失败：" + (yhDisasterEntities.size() - saveList.size()) + "用时  " + (endIn - startIn));
        update(iterable,saveList);
        SjtgfJghshYjSjdzbEntity sjtgfJghshYjSjdzbEntity = new SjtgfJghshYjSjdzbEntity();
        sjtgfJghshYjSjdzbEntity.setBmc("hddc_activefault");
        sjtgfJghshYjSjdzbEntity.setSjts(iterable);
        sjtgfJghshYjSjdzbEntity.setLch(Integer.valueOf("101"));
        reconciliationService.saveReconciliation(sjtgfJghshYjSjdzbEntity);
    }
    private void update(int iterable,List<HddcActivefaultPostgresqlEntity> saveList){
        List<ProxyVO6> proxyVOs=new ArrayList<>();
        for (int i=0;i<iterable;i++) {
            HddcActivefaultPostgresqlEntity pgEntity = saveList.get(i);
            ProxyVO6 proxyVO=new ProxyVO6();
            proxyVO.setUuid(pgEntity.getUuid());
            //proxyVO.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            proxyVO.setIsReportPg("1");
            proxyVOs.add(proxyVO);
        }
        superRepository.batchUpdate(proxyVOs);
    }
    @Override
    public void findDataUpdate() {
        LocalDateTime updateTime = repository.findUpdateTime();
        //查询新增数据
        List<HddcActivefaultPGEntity> yhDisasterEntities = hddcActivefaultPGNativeRepository.findYhDisastersUpdate(updateTime);
        if (yhDisasterEntities.size() == 0) {
            System.out.println("hddc_activefault:时间" + new Date() + ",修改查询了数据：" + yhDisasterEntities.size() + " 条");
            return;
        }
        Map<String, String> errorMap = new HashMap<>();
        List<String> list=new ArrayList<>();
        List<HddcActivefaultPostgresqlEntity> saveList = new ArrayList<>();
        int flag = 0;
        String startCode = null;
        try {
            for (HddcActivefaultPGEntity entity : yhDisasterEntities) {
                String uuid = entity.getUuid();
                String code = ProvinceCityAreaUtil.getCode(entity.getProvince(), entity.getCity(), entity.getArea());
                if (code == null) {
                    errorMap.put(uuid, "区划编码获取失败!");
                    // log.error("活动断层线hddc_activefault:时间" + new Date() + ",数据id:{}" + entity.getUuid() + ";区划:{}" +
                    //         entity.getProvince() + entity.getCity() + entity.getArea() + "的区划编码获取失败，请检查后再导入");
                    continue;
                }
                if (!pioneerCodeList.contains(code)) {
                    String cityCode=code.substring(0, 4) + "00";
                    if (!pioneerCodeList.contains(cityCode)){
                        if (!list.contains(entity.getProvince() + entity.getCity() + entity.getArea())){
                            list.add(entity.getProvince() + entity.getCity() + entity.getArea());
                            errorMap.put(entity.getProvince() + entity.getCity() + entity.getArea(), "不属于试点县!");
                        }
                        continue;
                    }
                }
                //检查字段值不为空
                StringBuilder errorMsg = new StringBuilder();
                Map<String, String> methods = new HashMap<>();
                setCheckFields(methods);

                ServerUtil.checkFieldNull(entity, methods, errorMsg);

                if (StringUtils.isNotEmpty(String.valueOf(errorMsg)) || errorMsg.length() > 0) {
                    errorMap.put(uuid, "必填项存在空值!");
                    // log.error("活动断层线hddc_activefault:时间" + new Date() + ",数据id:{}" + entity.getUuid() + ";错误信息:{}" + errorMsg +
                    //         "导入失败！");
                    continue;
                }
                if (!featureids.contains(entity.getFeature())){
                    errorMap.put(uuid, "断层类型不符合规范!");
                    continue;
                }
                if (!lastnewids.contains(entity.getLatestactiveperiod())){
                    errorMap.put(uuid, "最新活动年代不符合规范!");
                    continue;
                }
                HddcActivefaultPostgresqlEntity postgresqlEntity = new HddcActivefaultPostgresqlEntity();
                BeanUtils.copyProperties(entity, postgresqlEntity);
                postgresqlEntity.setDistrict(entity.getArea());
                postgresqlEntity.setFxpcDataidSjgl(entity.getUuid());

                Geometry geometry = GeometryUtil.setRecArea(entity.getExtends15());
                postgresqlEntity.setExtends5(geometry);

                String oldSitCode = null;
                if (flag == 0) {
                    flag++;
                    oldSitCode = repository.getGenerateSiteCode();
                } else {
                    oldSitCode = startCode;
                }
                String generateSiteCode = GenerateSiteCodeUtil.generateSiteCode(code, oldSitCode, "地震活动断层");
                startCode = generateSiteCode;
                postgresqlEntity.setFxpcDcdxbmSjgl(generateSiteCode);
                //根据名称获取行政编码
                if (!StringUtils.isEmpty(entity.getProvince()) && StringUtils.isEmpty(entity.getCity())) {
                    postgresqlEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                }
                if (!StringUtils.isEmpty(entity.getCity()) && StringUtils.isEmpty(entity.getArea())) {
                    postgresqlEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                    postgresqlEntity.setFxpcXzqhbmbSjgl(code.substring(0, 4) + "00");
                }
                if (!StringUtils.isEmpty(entity.getArea())) {
                    postgresqlEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                    postgresqlEntity.setFxpcXzqhbmbSjgl(code.substring(0, 4) + "00");
                    postgresqlEntity.setFxpcXzqhbmcSjgl(code);
                }
                //标识数据的当前状态，如果是新增数据，该字段为I；
                // 如果数据被更新过，该字段为U；如果数据被删除，该字段为D。
                if (entity.getIsValid().equals("0")) {
                    postgresqlEntity.setFxpcSjztSjgl("D");
                } else {
                    postgresqlEntity.setFxpcSjztSjgl("U");
                }
                //将创建时间转化成字符串形式
                if (entity.getCreateTime() != null) {
                    postgresqlEntity.setFxpcCreatetimeSjgl(DateUtil.getContainsHMS(entity.getCreateTime()));
                }
                if (entity.getUpdateTime() != null) {
                    postgresqlEntity.setFxpcUpdatetimeSjgl(DateUtil.getContainsHMS(entity.getUpdateTime()));
                }
                //统一都是默认040
                postgresqlEntity.setFxpcSshySjgl("040");
                //日期分片
                postgresqlEntity.setFxpcRqfpSjgl(DateUtil.getNotContainsHMS(new Date()));
                //批次号
                postgresqlEntity.setFxpcPchSjgl(DateUtil.getNotContainsHMS(new Date()));
                //审核流程状态
                postgresqlEntity.setFxpcShlcztSjgl(Constant.SHLCZT_ZZSH);
                //审核状态
                postgresqlEntity.setFxpcShztSjgl(Constant.SHZT_TG);
                saveList.add(postgresqlEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        long startIn = System.currentTimeMillis();
        int iterable = jgNativeRepository.batchUpdate1(saveList);
        long endIn = System.currentTimeMillis();
        if (errorMap.size() != 0) {
            log.error(errorMap);
        }
        System.out.println("表hddc_activefault:时间" + new Date() + ",修改数据：" + saveList.size() + " 条,用时  " + (endIn - startIn));
        update(iterable,saveList);
        SjtgfJghshYjSjdzbEntity sjtgfJghshYjSjdzbEntity = new SjtgfJghshYjSjdzbEntity();
        sjtgfJghshYjSjdzbEntity.setBmc("hddc_activefault");
        sjtgfJghshYjSjdzbEntity.setSjts(iterable);
        sjtgfJghshYjSjdzbEntity.setLch(Integer.valueOf("201"));
        reconciliationService.saveReconciliation(sjtgfJghshYjSjdzbEntity);
    }

    private void setCheckFields(Map<String, String> methods) {
        methods.put("id", "断层编号");
        methods.put("name", "断层名称");
        methods.put("feature", "断层性质");
        methods.put("latestactiveperiod", "最新活动时代");
    }
    private void initFeatureIds(){
        featureids.clear();
        featureids.add(111100);
        featureids.add(111101);
        featureids.add(111104);
        featureids.add(111102);
        featureids.add(111103);
        featureids.add(111110);
        featureids.add(111115);
        featureids.add(111116);
        featureids.add(111111);
        featureids.add(111112);
        featureids.add(111113);
        featureids.add(111120);
        featureids.add(111121);
        featureids.add(111122);
        featureids.add(111123);
        featureids.add(111125);
        featureids.add(111126);
        featureids.add(111127);
        featureids.add(111200);
        featureids.add(111201);
        featureids.add(111202);
        featureids.add(111203);
        featureids.add(111210);
        featureids.add(111211);
        featureids.add(111212);
        featureids.add(111213);
        featureids.add(111220);
        featureids.add(111221);
        featureids.add(111222);
        featureids.add(111223);
        featureids.add(111300);
        featureids.add(111301);
        featureids.add(111302);
        featureids.add(111303);
        featureids.add(111310);
        featureids.add(111311);
        featureids.add(111312);
        featureids.add(111313);
        featureids.add(111320);
        featureids.add(111321);
        featureids.add(111322);
        featureids.add(111323);
    }

    private void initNewIds(){
        lastnewids.clear();
        lastnewids.add(33320000);
        lastnewids.add(33320300);
        lastnewids.add(33320200);
        lastnewids.add(33310300);
        lastnewids.add(33310302);
        lastnewids.add(33310301);
        lastnewids.add(33310200);
        lastnewids.add(33310100);
        lastnewids.add(33310000);
        lastnewids.add(33300000);
        lastnewids.add(33310120);
        lastnewids.add(-33300000);
        lastnewids.add(33220000);
        lastnewids.add(33210000);
        lastnewids.add(33130000);
        lastnewids.add(33120000);
        lastnewids.add(33110000);
        lastnewids.add(33200000);
        lastnewids.add(33100000);
        lastnewids.add(33000000);
        lastnewids.add(32300000);
        lastnewids.add(32200000);
        lastnewids.add(32100000);
        lastnewids.add(32000000);
        lastnewids.add(31600000);
        lastnewids.add(31500000);
        lastnewids.add(31400000);
        lastnewids.add(31300000);
        lastnewids.add(31200000);
        lastnewids.add(31100000);
        lastnewids.add(31000000);
        lastnewids.add(23300000);
        lastnewids.add(20000000);
        lastnewids.add(10000000);
        lastnewids.add(-31100000);
    }
}
